/*
提交链接：https://leetcode.cn/problems/find-k-closest-elements/submissions/560400372
658. 找到 K 个最接近的元素-中等
完成日期：2024/9/1
滑动窗口
*/

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int n = arr.size();
        vector<int> result;
        // 找到最接近 x 的元素的索引
        int closest_index = 0;
        for (int i = 0; i < n; ++i) {
            if (abs(arr[i] - x) < abs(arr[closest_index] - x)) {
                closest_index = i;
            }
        }
        // 扩展窗口以获取 k 个最接近 x 的元素
        int left = closest_index;
        int right = closest_index;
        while (right - left + 1 < k) {
            if (left == 0) {
                right++;
            } else if (right == n - 1) {
                left--;
            } else if (abs(arr[left - 1] - x) <= abs(arr[right + 1] - x)) {
                left--;
            } else {
                right++;
            }
        }
        result.assign(arr.begin() + left, arr.begin() + right + 1);
        return result;
    }
};
